<?php
/**
 * Created by PhpStorm.
 * User: code001
 * Date: 20-6-18
 * Time: 上午11:38
 */
namespace App;

use App\Lib\Sdk\Manager;
use App\Models\Circle;
use App\Models\IReadable;
use App\Models\Send;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Model;

class  Helper {

    public static function formLoadModel(Form $form, IReadable $model, $disabledFields = null)
    {
        foreach ($model->attributeLabels() as $field => $attribute)
        {
            $placeHolder = isset($attribute['place_holder']) ? $attribute['place_holder'] : "";
            $required =  isset($attribute['required']) ? (bool)$attribute['required'] : false;
            $visible = isset($attribute['visible']) ? $attribute['visible'] : true;
            $disabled = false;
            if (is_array($disabledFields)) {
                $disabled = in_array($field, $disabledFields) ? true : false;
            }
            if (is_bool($disabledFields)) {
                $disabled = $disabledFields;
            }
            if (!$visible) continue;
            if (!is_array($attribute)) {
                $col = $form->text($field, $attribute)->placeholder($placeHolder)->value($model->getAttribute($field));
            } else {
                switch ($attribute['type']) {
                    case "time":
                        $form->time($field, $attribute['label'])->value($model->getAttribute($field));
                        break;
                    case "text":
                        $col = $form->text($field, $attribute['label'])
                            ->placeholder($placeHolder);
                        if ($required) {
                            $col->required();
                        }
                        if ($disabled) {
                            $col->disable();
                        }
                        $col->value($model->getAttribute($field));
                        break;
                    case "number":
                    case "integer":
                    $col = $form->number($field, $attribute['label'])
                             ->placeholder($placeHolder)
                             ->min(0)
                             ->value($model->getAttribute($field));
                        if ($required) {
                            $col->required();
                        }
                        if ($disabled) {
                            $col->disable();
                        }
                        break;
                    case "rate":
                        $col = $form->rate($field, $attribute['label'])
                            ->placeholder($placeHolder)
                            ->value($model->getAttribute($field));
                        break;
                    case "radio":
                        $col = $form->radio($field, $attribute['label'])
                            ->options($attribute['options'])
                            ->required($required)
                            ->value($model->getAttribute($field));
                        break;
                    case "password":
                        $col = $form->password($field, $attribute['label']);
                        if ($required) {
                            $col->required();
                        }
                        if ($disabled) {
                            $col->disable();
                        }
                        break;
                    case "checkbox":
                        $col = $form->checkbox($field, $attribute['label'])
                            ->options($attribute['options'])
                            ->required($required)
                            ->value($model->getAttribute($field));
                        break;
                    case "select":
                        $col = $form->select($field, $attribute['label'])
                            ->options($attribute['options'])
                            ->required($required)
                            ->value($model->getAttribute($field));
                        break;
                }
            }
            if ($required) {
                $col->required();
            }
        }
    }


    public static function gridLoadModel(Grid $grid, IReadable $model)
    {
        foreach ($model->attributeLabels() as $field => $attribute)
        {
            $callable = null;
            if (isset($attribute['callable'])) {
                $callable = $attribute['callable'];
            }
            if (!is_array($attribute)) {
                $grid->column($field, $attribute);
            } else {
                switch ($attribute['type']) {
                    case "text":
                        $g = $grid->column($field, $attribute['label']);
                        $width = isset($attribute['width']) ? $attribute['width'] : false;
                        if ($width !== false) {
                            $g->width($width);
                        }
                        $map = isset($attribute['map']) ? $attribute['map'] : [];
                        if (!empty($map)) {
                            $g->display(function($col) use ($map) {
                                return $map[$col];
                            });
                        }
                        if (!is_null($callable)) {
                            $g->display(function($col) use($callable) {
                                return call_user_func_array($callable, [$col]);
                            });
                        }
                        break;
                    case "integer":
                        $grid->column($field, $attribute['label']);
                        break;
                }
            }
        }
    }

    public static function loadForm(\Encore\Admin\Widgets\Form $form) {
        if (!$form instanceof IReadable) {
            throw new \Exception("必须是IReadable类");
        }
        foreach ($form->attributeLabels() as $field => $attribute)
        {
            $required =  isset($attribute['required']) ? (bool)$attribute['required'] : false;
            $placeHolder = isset($attribute['place_holder']) ? $attribute['place_holder'] : "";
            $value =  isset($attribute['value']) ? $attribute['value'] : "";
            $visible = isset($attribute['visible']) ? $attribute['visible'] : true;
            if (!$visible) continue;
            if (!is_array($attribute)) {
                $col = $form->text($field, $attribute)->placeholder($placeHolder)->value($value);
            } else {
                switch ($attribute['type']) {
                    case "text":
                        $col = $form->text($field, $attribute['label'])
                            ->placeholder($placeHolder)
                            ->default($value);
                        break;
                    case "number":
                        $value = (float)$value;
                        $col = $form->number($field, $attribute['label'])
                            ->placeholder($placeHolder)
                            ->min(0)
                            ->default($value);
                        break;
                    case "rate":
                        $col = $form->rate($field, $attribute['label'])
                            ->placeholder($placeHolder)
                            ->default($value);
                        break;
                    case "integer":
                        $value = (int)$value;
                        $col = $form->number($field, $attribute['label'])
                            ->min(0)
                            ->default($value);
                        break;
                    case "radio":
                        $col = $form->radio($field, $attribute['label'])
                            ->options($attribute['options'])
                            ->default($value);
                        break;
                    case "password":
                        $col = $form->password($field, $attribute['label'])  ->required($required)
                            ->default($value);
                        break;
                    case "checkbox":
                        $value = (array)$value;
                        $col = $form->checkbox($field, $attribute['label'])
                            ->options($attribute['options'])
                            ->default($value);
                        break;
                    case "select":
                        $col = $form->select($field, $attribute['label'])
                            ->options($attribute['options'])
                            ->default($value);
                        break;
                }
            }
            if ($required) {
                $col->required();
            }
        }
    }


    public static function getConfigByUid($uid = null)
    {
        if (is_null($uid)) {
            $uid = \Encore\Admin\Facades\Admin::guard()->id();
        }
        return \App\Models\User::getConfig($uid);
    }

    public static function imgToBase64($url) {

        $img_base64 = '';
        $ctx = stream_context_create(array(
                'http' => array(
                    'timeout' => 3
                )
            )
        );
        $stream = file_get_contents($url, null, $ctx);

        $isWin = strtoupper(substr(PHP_OS,0,3))==='WIN';
        if ($isWin) {
            $tmp = "C:\\Users\\administrator\\AppData\\Local\\Temp\\";
        } else {
            $tmp = "/tmp/";
        }
        $img_file =$tmp. rand(100,10000);
        file_put_contents($img_file, $stream);
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限
            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }

                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

            }
            fclose($fp);
        }
        unlink($img_file);
        return $img_base64; //返回图片的base64
    }


    public static function convertCouponLinkOfSend(Send $send, $uid)
    {
        $content = $send->content;
        $template = \GuzzleHttp\json_decode($send->raw_data, true);
        $taobaoSpider = Manager::getSpider(Manager::TAOBAO);
        $jdSpider = Manager::getSpider(Manager::JD);
        $pddSpider = Manager::getSpider(Manager::PDD);
        $user  = \App\Models\User::where("id", $uid)->first();
        $searchId = isset($template['search_id']) ? $template['search_id'] : "";
        $extra = ['uid' => $user->tuid, 'search_id' => $searchId];
        switch ($template['shop']) {
            case "淘宝":
            case "天猫":
                $link = $taobaoSpider->getHcai([
                     'item_id' => $template['skuId']
                 ], $uid);
                 $content = str_replace("{淘口令}", $link, $content);
                break;
            case "京东":
                $link = $jdSpider->getLink([
                    'goods_id' => $template['skuId'],
                    'discount_link' => $template['couponLink']
                ], $uid, $extra);
                $content = str_replace("{商品链接}", $link, $content);
                break;
            case "拼多多":
                $link = $pddSpider->generateLink([
                    'goods_id' => $template['skuId'],
                ], $uid, $extra);
                $content = str_replace("{商品链接}", $link, $content);
                break;
        }
        return urldecode($content);
    }

    public static function convertCouponLinkOfCircle(Circle $send, $uid)
    {
        $template = \GuzzleHttp\json_decode($send->raw_data, true);
        $taobaoSpider = Manager::getSpider(Manager::TAOBAO);
        $jdSpider = Manager::getSpider(Manager::JD);
        $pddSpider = Manager::getSpider(Manager::PDD);
        $user  = \App\Models\User::where("id", $uid)->first();
        $searchId = isset($template['search_id']) ? $template['search_id'] : "";
        $extra = ['uid' => $user->tuid, 'search_id' => $searchId];
        $link = "";
        switch ($template['shop']) {
            case "淘宝":
            case "天猫":
                $link = $taobaoSpider->getHcai([
                    'item_id' => $template['skuId']
                ], $uid, $user->tuid);
                break;
            case "京东":
                $link = $jdSpider->getLink([
                    'goods_id' => $template['skuId'],
                    'discount_link' => $template['couponLink']
                ], $uid, $extra);
                break;
            case "拼多多":
                $link = $pddSpider->generateLink([
                    'goods_id' => $template['skuId'],
                ], $uid, $extra);
                break;
            default:
        }
        return $link;
    }
}